import os
from .models import *
import json
import datetime
import re
import hashlib
from django.db import connection
import csv
from urllib import parse
from django.forms.models import model_to_dict

def save_test_case(base_dir, test_casess):
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)
    test_cases = {}
    index = 0
    for c in test_casess:
        input_content = c.get('input')
        output_content = c.get('output')
        output_content = re.sub(" *\\n", "\n", output_content)
        one_info = {
            "input_size": len(input_content),
            "input_name": f"{index + 1}.in",
            "output_size": len(output_content),
            "output_name": f"{index + 1}.out",
            "stripped_output_md5": hashlib.md5(output_content.rstrip().encode("utf-8")).hexdigest()
        }
        test_cases[index] = one_info
        with open(os.path.join(base_dir, str(index + 1) + ".in"), "w", encoding="utf-8") as f:
            f.write(input_content)
        with open(os.path.join(base_dir, str(index + 1) + ".out"), "w", encoding="utf-8") as f:
            f.write(output_content)
        index += 1
    info = {
        "spj": False,
        "test_cases": test_cases
    }
    with open(os.path.join(base_dir, "info"), "w", encoding="utf-8") as f:
        f.write(json.dumps(info, indent=4))

# 导入
def importQT():

    tags = ProblemTag.objects.all()
    tagDic = {}
    for tag in tags:
        tagDic[tag.name] = tag

    qt2json = os.path.join('data', 'qt2.json')
    with open(qt2json, 'r', encoding='utf-8') as f:
        ps = json.load(f)

    for p in ps:
        # "tags": ["入门", "语法基础"]
        qid = p['href'][9:]

        np = Problem()
        np._id = 'QT' + qid
        np.title = p['title']
                
        np.description = p['tmms']
        if 'srgs' in p:
            np.input_description = p['srgs']
        else:
            np.input_description = ''
        if 'scgs' in p:
            np.output_description = p['scgs']
        else:
            np.output_description = ''

        np.solution = ''
        
        if 'yls' in p:
            np.samples = json.dumps(p['yls'])
            np.test_case_id = np._id
            save_test_case(os.path.join('data', 'qingteng', np._id), p['yls'])
        else:
            np.samples = ''

        if 'ts' in p:
            np.hint = p['ts']
        else:
            np.hint = ''

        np.create_time = datetime.datetime.now()

        np.time_limit = int(p['tm'])                          
        np.memory_limit = int(p['mem'])

        np.visible = False
        np.submission_number = 0
        np.accepted_number = 0
            
        np.difficulty = '1'

        np.source = '青滕'
        
        print(p['tags'])
        print(json.dumps(model_to_dict(np), ensure_ascii=False))


        np.save()

        for qt in p['tags']:
            if qt in tagDic:
                t = tagDic[qt]
                np.tags.add(t)
            else:
                t = ProblemTag()
                t.name = qt.rstrip()
                t.save()
                tagDic[qt] = t
                np.tags.add(t)
